from flask import Blueprint, request, jsonify
from app.models.Skillc2 import Order, Book, Food, User, db
from datetime import datetime

order_bp = Blueprint('order', __name__)

@order_bp.route('/orders', methods=['GET'])
def get_order_list():
    """获取订单列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        user_id = request.args.get('user_id', type=int)
        order_type = request.args.get('type')
        state = request.args.get('state')
        
        # 构建查询
        query = Order.query
        
        # 应用过滤条件
        if user_id:
            query = query.filter_by(UserId=user_id)
        if order_type:
            query = query.filter_by(Type=order_type)
        if state:
            query = query.filter_by(State=state)
            
        # 按时间倒序排序
        query = query.order_by(Order.OrderTime.desc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        items = [item.to_dict() for item in pagination.items]
        
        data = {
            'items': items,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': pagination.page,
            'has_next': pagination.has_next,
            'has_prev': pagination.has_prev
        }
        
        return jsonify({'status': 'success', 'message': '获取订单列表成功', 'data': data})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 400

@order_bp.route('/orders/<int:order_id>', methods=['GET'])
def get_order_detail(order_id):
    """获取订单详情"""
    try:
        order = Order.query.get_or_404(order_id)
        return jsonify({'status': 'success', 'message': '获取订单详情成功', 'data': order.to_dict()})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 400

@order_bp.route('/orders', methods=['POST'])
def create_order():
    """创建订单"""
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        order_type = data.get('type')
        item_id = data.get('item_id')
        quantity = data.get('quantity', 1)
        
        if not all([user_id, order_type, item_id]):
            return jsonify({'status': 'error', 'message': '用户ID、订单类型和商品ID不能为空'}), 400
            
        # 验证数量是否大于0
        if not isinstance(quantity, int) or quantity <= 0:
            return jsonify({'status': 'error', 'message': '商品数量必须为大于0的整数'}), 400
            
        # 验证用户是否存在
        user = User.query.get(user_id)
        if not user:
            return jsonify({'status': 'error', 'message': '用户不存在'}), 400
            
        # 根据订单类型获取商品价格
        total_price = 0
        if order_type == 'book':
            book = Book.query.get(item_id)
            if not book:
                return jsonify({'status': 'error', 'message': '书籍不存在'}), 400
            total_price = float(book.Price) * quantity
        elif order_type == 'food':
            food = Food.query.get(item_id)
            if not food:
                return jsonify({'status': 'error', 'message': '食品不存在'}), 400
            total_price = float(food.FoodPrice) * quantity
        else:
            return jsonify({'status': 'error', 'message': '不支持的订单类型'}), 400
            
        # 创建订单
        order = Order(
            UserId=user_id,
            Type=order_type,
            ItemId=item_id,
            Quantity=quantity,
            TotalPrice=total_price
        )
        
        db.session.add(order)
        db.session.commit()
        
        return jsonify({'status': 'success', 'message': '创建订单成功', 'data': order.to_dict()})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 400

@order_bp.route('/orders/<int:order_id>', methods=['PUT'])
def update_order_state(order_id):
    """更新订单状态"""
    try:
        order = Order.query.get_or_404(order_id)
        data = request.get_json()
        new_state = data.get('state')
        
        if not new_state:
            return jsonify({'status': 'error', 'message': '订单状态不能为空'}), 400
            
        # 验证状态转换的合法性
        valid_states = ['pending', 'paid', 'completed', 'cancelled']
        if new_state not in valid_states:
            return jsonify({'status': 'error', 'message': '无效的订单状态'}), 400
            
        # 更新状态和相应的时间
        order.State = new_state
        if new_state == 'paid':
            order.PayTime = datetime.now()
        elif new_state == 'completed':
            order.CompleteTime = datetime.now()
            
        db.session.commit()
        return jsonify({'status': 'success', 'message': '更新订单状态成功', 'data': order.to_dict()})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 400

@order_bp.route('/orders/<int:order_id>', methods=['DELETE'])
def delete_order(order_id):
    """删除订单（仅允许删除未支付的订单）"""
    try:
        order = Order.query.get_or_404(order_id)
        
        if order.State != 'pending':
            return jsonify({'status': 'error', 'message': '只能删除未支付的订单'}), 400
            
        db.session.delete(order)
        db.session.commit()
        
        return jsonify({'status': 'success', 'message': '删除订单成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 400 